//
//  OASelectDepartmentController.m
//  OASystem
//
//  Created by zhoupengfei on 15/4/29.
//  Copyright (c) 2015年 zpf. All rights reserved.
//
#import "OANameListController.h"
#import "OAExpendViewController.h"
#import "OASelectDepartmentController.h"
#import "OAAttachmentsModel.h"
#import "HttpTools.h"
#import "GDataDefines.h"
#import "OADepartmentModel.h"
#import "OASelectPersonController.h"
#import "MBProgressHUD.h"
#import "OASubNameListModel.h"
#import "OANameListModel.h"
#import "OASelectPersonSecondController.h"
#import "Toast+UIView.h"
#import "ComingworkongController.h"
@interface OASelectDepartmentController ()


@property(nonatomic,strong)NSMutableArray * personArray;

@property(nonatomic,strong)NSMutableArray * groupArray; //group
@property(nonatomic,strong)NSMutableArray * rowArray;
@property(nonatomic,copy)NSString * setpString;
@property(nonatomic,copy)    NSString * info ;
@end

@implementation OASelectDepartmentController



-(NSMutableArray*)personArray{
    if (_personArray ==nil) {
        _personArray = [NSMutableArray array];
    }
    return _personArray;
}

-(NSMutableArray*)groupArray{
    
    if (_groupArray == nil) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}

-(NSMutableArray*)rowArray{
    if (_rowArray == nil) {
        _rowArray = [NSMutableArray array];
    }
    return _rowArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"下一环节";
        _operationItem.enabled = YES;

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
}


-(void)setupRightItems{
    _operationItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(operationACtion)];
    self.navigationItem.rightBarButtonItem = _operationItem;
    
}

#pragma mark 确定提交
-(void)operationACtion{
            [self loadInfoData:_string]; //点击选择的 departmanet 获得相应的数据

_operationItem.enabled = NO;
    
    
}

-(NSMutableArray*)dataWith:(NSString*)dataString
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arrData = [[NSMutableArray alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *users = [rootElement children];
    for (int i = 0;i<[users count];i++) {
        GDataXMLElement *ele = [users objectAtIndex:i];
        if ([[ele name] isEqualToString:@"环节"]){
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [[ele attributeForName:@"流向"] stringValue];
            [arrData addObject:model];
        }
    }
    return arrData;
}


-(NSString *)returnString
{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        OAAttachmentsModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.departments.count;
}


#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellIdentifier = @"cellIdentifier";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell ==nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    OADepartmentModel * model = self.departments[indexPath.row];
    cell.textLabel.text = model.department;
    if (model.isSelected) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * string = self.subItems[indexPath.row];
    for (int index = 0; index < self.departments.count; index++) {
        OADepartmentModel * model = self.departments[index];
        
        if (index == indexPath.row) {
            model.isSelected = YES;
                        _string = string;

                                [self setupRightItems];

//            [self loadInfoData:string]; //点击选择的 departmanet 获得相应的数据
        
           
        }else{
            model.isSelected = NO;
        }
    }
    
    [self.tableView reloadData];
}

#pragma mark 点击选择的 departmanet 获得相应的数据
-(void)loadInfoData:(NSString*)string{
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = nil;
    if (self.fileId !=nil) {
        array = @[@{@"unid":self.fileId},@{@"userId":userId},@{@"segment":string},@{@"famxml":self.body}];
    }else if (self.detailPatchModel != nil){
    if ([string isEqualToString:@"<结束>"]) {
    string = [string stringByReplacingOccurrencesOfString:@"<" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@">" withString:@""];
}
    
    
        array = @[@{@"unid":self.detailPatchModel.fileId},@{@"userId":userId},@{@"segment":string},@{@"famxml":self.body}];
    }
  
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetRetStaffList success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        [self getListWithJson:JSON];
//        [self setupRightItems];
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}

-(void)getListWithJson:(id)json{
    [self.groupArray removeAllObjects];
    [self.rowArray removeAllObjects];
    [self.personArray removeAllObjects];
    
    
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *infoArray= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoArray count];i++)
    {
        GDataXMLElement *infoElement = [infoArray objectAtIndex:i];
        self.info = [infoElement stringValue];
    }
    
    NSArray *setpArray= [rootElement elementsForName:@"环节"];
    for (int i = 0;i<[setpArray count];i++)
    {
        GDataXMLElement *setpElement = [setpArray objectAtIndex:i];
        self.setpString = [setpElement stringValue];
    }
    
    
    if ([self.info isEqualToString:@"13"]) {
        NSArray *users = [rootElement elementsForName:@"成员"];
        for (int i = 0;i<[users count];i++) {
            GDataXMLElement *ele = [users objectAtIndex:i];
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [ele stringValue];
            [self.personArray addObject: model];
        
        }

    }else if ([self.info isEqualToString:@"14"]){
        
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
        //获取根节点
        GDataXMLElement *rootElement = [doc rootElement];
        OANameListModel * titleModel = [[OANameListModel alloc]init];
        NSArray *ParentNodeData= [rootElement elementsForName:@"ParentNode"];
        for (int i = 0;i<[ParentNodeData count];i++)
        {
            GDataXMLElement *ParentElement = [ParentNodeData objectAtIndex:i];
            NSArray *ParentData= [ParentElement elementsForName:@"Parent"];
            for (int j = 0; j<[ParentData count]; j++)
            {
                GDataXMLElement *element = [ParentData objectAtIndex:j];
                titleModel.uid = [[element attributeForName:@"uid"] stringValue];
                titleModel.value = [[element attributeForName:@"value"]stringValue];
            }
        }
        
        NSArray *PartNodeData= [rootElement elementsForName:@"PartNode"];
        for (int i = 0;i<[PartNodeData count];i++)
        {
            GDataXMLElement *PNodeElement = [PartNodeData objectAtIndex:i];
            NSArray *PNodeData= [PNodeElement elementsForName:@"PNode"];
            for (int j = 0; j<[PNodeData count]; j++)
            {
                OANameListModel * subjectModel = [[OANameListModel alloc]init];
                GDataXMLElement *element = [PNodeData objectAtIndex:j];
                subjectModel.uid = [[element attributeForName:@"uid"] stringValue];
                subjectModel.value = [[element attributeForName:@"value"]stringValue];
                subjectModel.subArray  = [NSMutableArray array];
                [self.groupArray addObject:subjectModel];
            }
        }
        
        NSArray *PersonNodeData= [rootElement elementsForName:@"PersonNode"];
        for (int i = 0;i<[PersonNodeData count];i++)
        {
            GDataXMLElement *PersonElement = [PersonNodeData objectAtIndex:i];
            NSArray *PersonData= [PersonElement elementsForName:@"Person"];
            for (int j = 0; j<[PersonData count]; j++)
            {
                OASubNameListModel * subModel = [[OASubNameListModel alloc]init];
                GDataXMLElement *element = [PersonData objectAtIndex:j];
                subModel.pid = [[element attributeForName:@"pid"] stringValue];
                subModel.value = [[element attributeForName:@"value"]stringValue];
                [self.rowArray addObject:subModel];
            }
        }
        
        for (OANameListModel * nameLisModel in self.groupArray) {
            for (OASubNameListModel * subModel in self.rowArray) {
                if ([nameLisModel.uid isEqualToString:subModel.pid]) {
                    [nameLisModel.subArray addObject:subModel];
                }
            }
        }
    
        
    }
        [self push];

 }
- (void)push{
if ( [self.info isEqualToString:@"11"]) {
    
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        [self.view makeToast:@"提交成功"];
    }
    else if ([self.info isEqualToString:@"15"]){
    
   [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
       [self.view makeToast:@"归档成功"];

    }else if ([self.info isEqualToString:@"18"]){
          UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OANameListController * expendVC = (OANameListController*)[storyBoard instantiateViewControllerWithIdentifier:@"NameLIstID"];
//    listVC.delegate = self;
//
//    self.namelist = listVC;
//    [self.navigationController pushViewController:listVC animated:YES];
// OAExpendViewController * expendVC = [[OAExpendViewController alloc] init];
//        expendVC.type = UnitDataType;
expendVC.fileId = self.detailPatchModel.fileId;
 expendVC.body = self.body;
expendVC.setpString = self.setpString;

expendVC.seltype = @"daiban";
//        expendVC.type = UnitDataType;

//         expendVC.identifierString = @"txsfb";
         [self.navigationController pushViewController:expendVC animated:YES];

    }


       else{
    
        for (int index = 0; index < self.departments.count; index++) {
            OADepartmentModel * model = self.departments[index];
            if (model.isSelected) {
                if (self.personArray.count >0) {
                    OASelectPersonController * selectPersonVC = [[OASelectPersonController alloc]init];
                    selectPersonVC.personArray = self.personArray;
                    selectPersonVC.body = self.body;
                    selectPersonVC.setpString = self.setpString;
                    if (self.fileId ) {
                        selectPersonVC.fileId = self.fileId;
                    }else if (self.detailPatchModel){
                        selectPersonVC.fileId = self.detailPatchModel.fileId;
                    }
                                         selectPersonVC.hidesBottomBarWhenPushed = YES;

                    [self.navigationController pushViewController:selectPersonVC animated:YES];
                }else{
                    OASelectPersonSecondController * selectPersonVC = [[OASelectPersonSecondController alloc]init];
                    selectPersonVC.personArray = self.personArray;
                    selectPersonVC.body = self.body;
                    selectPersonVC.setpString = self.setpString;
                    if (self.fileId ) {
                        selectPersonVC.fileId = self.fileId;
                    }else if (self.detailPatchModel){
                        selectPersonVC.fileId = self.detailPatchModel.fileId;
                    }
                    selectPersonVC.groupArray = self.groupArray;
                    selectPersonVC.rowArray = self.rowArray;
                                                             selectPersonVC.hidesBottomBarWhenPushed = YES;

                    [self.navigationController pushViewController:selectPersonVC animated:YES];
                }
                
                break;
            }
        }

    
    }

}
@end
